<template>
  <div class="statistics-container">
    <PageHeader title="生产统计">
      <template #actions>
        <el-radio-group v-model="selectedPeriod" size="large" @change="fetchProductionHistory">
          <el-radio-button label="day">日</el-radio-button>
          <el-radio-button label="week">周</el-radio-button>
          <el-radio-button label="month">月</el-radio-button>
        </el-radio-group>
      </template>
    </PageHeader>

    <main class="statistics-content">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>生产趋势</span>
              </div>
            </template>
            <div class="chart-container">
              <!-- 添加调试信息 -->
              <div v-if="productionHistory.length === 0" class="debug-info" style="position: absolute; top: 10px; left: 10px; font-size: 12px; color: #f56c6c; z-index: 10;">
                无数据: {{ selectedPeriod }}
              </div>

              <LineChart
                v-if="chartData.datasets[0]?.data.length > 0"
                :chartData="chartData"
                :options="chartOptions"
              />
              <div v-else class="no-data">暂无数据 ({{ selectedPeriod }})</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="stats-row">
        <el-col :span="8">
          <el-card class="stats-card">
            <template #header>
              <div class="card-header">
                <span>生产总量</span>
              </div>
            </template>
            <div class="stats-value">{{ formatNumber(totalProduction) }} 米</div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card class="stats-card">
            <template #header>
              <div class="card-header">
                <span>平均生产速度</span>
              </div>
            </template>
            <div class="stats-value">{{ formatNumber(averageSpeed) }} 米/分钟</div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card class="stats-card">
            <template #header>
              <div class="card-header">
                <span>最高生产速度</span>
              </div>
            </template>
            <div class="stats-value">{{ formatNumber(maxSpeed) }} 米/分钟</div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>设备生产统计</span>
              </div>
            </template>
            <el-table :data="deviceStats" style="width: 100%">
              <el-table-column prop="device_id" label="设备ID" />
              <el-table-column prop="name" label="设备名称" />
              <el-table-column prop="total_production" label="生产总量">
                <template #default="scope">
                  {{ formatNumber(scope.row.total_production) }} 米
                </template>
              </el-table-column>
              <el-table-column prop="average_speed" label="平均速度">
                <template #default="scope">
                  {{ formatNumber(scope.row.average_speed) }} 米/分钟
                </template>
              </el-table-column>
              <el-table-column prop="max_speed" label="最高速度">
                <template #default="scope">
                  {{ formatNumber(scope.row.max_speed) }} 米/分钟
                </template>
              </el-table-column>
              <el-table-column prop="uptime_percentage" label="运行时间">
                <template #default="scope">
                  {{ formatNumber(scope.row.uptime_percentage) }}%
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useDashboardStore } from '@/stores'
import { LineChart } from 'vue-chart-3'
import { Chart, registerables } from 'chart.js'
import PageHeader from '../components/PageHeader.vue'

// Register Chart.js components
Chart.register(...registerables)

const store = useDashboardStore()
const selectedPeriod = ref('day')
const deviceStats = ref([])

// Mock data for device statistics (in a real app, this would come from the API)
const generateMockDeviceStats = () => {
  return store.devices.map(device => {
    return {
      device_id: device.device_id,
      name: device.name,
      total_production: Math.random() * 5000 + 1000,
      average_speed: Math.random() * 20 + 10,
      max_speed: Math.random() * 30 + 20,
      uptime_percentage: Math.random() * 30 + 70
    }
  })
}

// 生成日趋势图的模拟数据
const generateMockDayData = () => {
  const now = new Date()
  const data = []

  // 生成24小时的数据点，每小时一个
  for (let i = 0; i < 24; i++) {
    const timestamp = new Date(now.getFullYear(), now.getMonth(), now.getDate(), i, 0, 0)

    // 生成随机的生产速度和生产长度
    const production_speed = Math.random() * 30 + 10 // 10-40 米/分钟
    const production_length = Math.random() * 500 + 200 // 200-700 米

    data.push({
      timestamp: timestamp.toISOString(),
      production_speed,
      production_length
    })
  }

  return data
}

// Computed properties
const productionHistory = computed(() => store.productionHistory)

// Calculate statistics
const totalProduction = computed(() => {
  if (!productionHistory.value.length) return 0
  return productionHistory.value.reduce((sum, item) => sum + (item.production_length || 0), 0)
})

const averageSpeed = computed(() => {
  if (!productionHistory.value.length) return 0
  const speeds = productionHistory.value.filter(item => item.production_speed)
  if (!speeds.length) return 0
  return speeds.reduce((sum, item) => sum + item.production_speed, 0) / speeds.length
})

const maxSpeed = computed(() => {
  if (!productionHistory.value.length) return 0
  return Math.max(...productionHistory.value.map(item => item.production_speed || 0))
})

// Chart data
const chartData = computed(() => {
  console.log('Computing chart data for period:', selectedPeriod.value)
  console.log('Production history length:', productionHistory.value.length)

  if (productionHistory.value.length === 0) {
    console.log('No production history data available')
    return {
      labels: [],
      datasets: []
    }
  }

  const labels = productionHistory.value.map(item => {
    if (!item.timestamp) {
      console.log('Item missing timestamp:', item)
      return ''
    }
    const date = new Date(item.timestamp)
    const formattedDate = selectedPeriod.value === 'day'
      ? date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      : date.toLocaleDateString('zh-CN')
    return formattedDate
  })

  const speedData = productionHistory.value.map(item => {
    if (item.production_speed === undefined) {
      console.log('Item missing production_speed:', item)
      return 0
    }
    return item.production_speed
  })

  const lengthData = productionHistory.value.map(item => {
    if (item.production_length === undefined) {
      console.log('Item missing production_length:', item)
      return 0
    }
    return item.production_length
  })

  console.log('Chart labels:', labels)
  console.log('Speed data:', speedData)
  console.log('Length data:', lengthData)

  return {
    labels,
    datasets: [
      {
        label: '生产速度 (米/分钟)',
        data: speedData,
        borderColor: '#409EFF',
        backgroundColor: 'rgba(64, 158, 255, 0.2)',
        tension: 0.4,
        yAxisID: 'y'
      },
      {
        label: '生产长度 (米)',
        data: lengthData,
        borderColor: '#67C23A',
        backgroundColor: 'rgba(103, 194, 58, 0.2)',
        tension: 0.4,
        yAxisID: 'y1'
      }
    ]
  }
})

const chartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  scales: {
    y: {
      type: 'linear',
      display: true,
      position: 'left',
      title: {
        display: true,
        text: '生产速度 (米/分钟)'
      }
    },
    y1: {
      type: 'linear',
      display: true,
      position: 'right',
      title: {
        display: true,
        text: '生产长度 (米)'
      },
      grid: {
        drawOnChartArea: false
      }
    }
  }
}

// Methods
const formatNumber = (num) => {
  if (num === undefined || num === null) return '0'
  return num.toLocaleString('zh-CN', { maximumFractionDigits: 2 })
}

const fetchProductionHistory = async () => {
  console.log('Fetching production history for period:', selectedPeriod.value)

  // 特殊处理日趋势图数据
  if (selectedPeriod.value === 'day') {
    console.log('特殊处理日趋势图数据')
    // 生成24小时的模拟数据
    const mockDayData = generateMockDayData()
    console.log('生成的模拟日趋势数据:', mockDayData)
    // 直接设置到 store 中
    store.productionHistory = mockDayData
  } else {
    // 周和月使用正常的 API 请求
    await store.fetchProductionHistory(selectedPeriod.value)
  }

  console.log('Production history data:', store.productionHistory)
  // In a real app, you would fetch device stats from the API
  deviceStats.value = generateMockDeviceStats()
}

// Lifecycle hooks
onMounted(async () => {
  console.log('Component mounted, initializing...')
  try {
    await store.fetchDeviceStatus()
    console.log('Device status fetched successfully')

    // 确保默认选择日期间
    selectedPeriod.value = 'day'
    console.log('Selected period set to:', selectedPeriod.value)

    await fetchProductionHistory()
    console.log('Production history fetched successfully')
  } catch (error) {
    console.error('Error during component initialization:', error)
  }
})
</script>

<style scoped>
.statistics-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
}

/* 使用共享的 PageHeader 组件样式 */

.statistics-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 400px;
}

.no-data {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #909399;
}

.stats-row {
  margin-top: 20px;
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
}

.stats-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  padding: 20px 0;
}
</style>
